package common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

@Component
public class MyDisReentrantLock extends AbstractSerializer {
    private final char separator = ':';
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static String clientId;

    static {
        try {
            clientId = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param c
     * @param key
     * @param expireTime 秒
     * @return
     */
    public boolean lock(Class c, String key, long expireTime) {
        return this.redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection conn)
                    throws DataAccessException {
                byte[] keyBytes = serializeKey("bus" + c.getSimpleName() + separator + key);
                return conn.set(keyBytes, serialize(clientId),Expiration.seconds(expireTime), RedisStringCommands.SetOption.ifAbsent());
            }
        });
    }

    /**
     * @param c
     * @param key
     * @return
     */
    public boolean unLock(Class c,String key) {
        return this.redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection conn)
                    throws DataAccessException {
                conn.del(serializeKey("bus" + c.getSimpleName() + separator + key));
                return true;
            }
        });
    }
}
